package home.fragment;

import static android.content.ContentValues.TAG;
import static android.os.Looper.getMainLooper;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.xfengshopping.MainActivity;
import com.example.xfengshopping.R;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import LOGIN.login;
import base.BaseFragment;
import home.fragment.Adapter.GridViewAdapter;
import LOGIN.LoginFragment;

public class HomeFragment extends BaseFragment {

    private View rootView;
    private NestedScrollView svHome;
    private LinearLayout hometop;
    private ImageView ivHomeLeft;
    private TextView tvHomeLogin;
    private ImageView ivHomeLogin;
    private Banner banner;
    private RecyclerView recyclerViewHot, recyclerViewNew, recyclerViewRecommend;
    private GridView gridView;

    private final List<Carousel> carousels = new ArrayList<>();
    private final List<Goods> hotGoodses = new ArrayList<>();
    private final List<Goods> newGoodses = new ArrayList<>();
    private final List<Goods> recommendGoodses = new ArrayList<>();

    private GoodsAdapter hotAdapter, newAdapter, recommendAdapter;
    private GridViewAdapter gridAdapter;

    private boolean isLoading = false;
    private boolean isViewCreated = false;
    private boolean isDataLoaded = false;

    // 使用单线程池管理网络请求
    private final ExecutorService executorService = Executors.newSingleThreadExecutor();

    // 弱引用Handler防止内存泄漏
    private static class SafeHandler extends Handler {
        private final WeakReference<HomeFragment> fragmentRef;

        SafeHandler(HomeFragment fragment) {
            super(getMainLooper());
            this.fragmentRef = new WeakReference<>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            HomeFragment fragment = fragmentRef.get();
            if (fragment == null || fragment.isDetached() || !fragment.isViewCreated) return;

            if (msg.what == 1) {
                fragment.updateUI();
            } else if (msg.what == 0) {
                Toast.makeText(fragment.mContext, "数据加载失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private final Handler handler = new SafeHandler(this);

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d(TAG, "HomeFragment: onCreateView");

        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_home, container, false);
            initViews(rootView);
            initRecyclerViews();
            setupListeners();
            isViewCreated = true;
        } else {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
        }

        return rootView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.d(TAG, "HomeFragment: onViewCreated");

        if (!isDataLoaded) {
            loadData();
            isDataLoaded = true;
        }
    }

    @SuppressLint("WrongViewCast")
    private void initViews(View view) {
        svHome = view.findViewById(R.id.sv_home);
        hometop = view.findViewById(R.id.home_top);
        ivHomeLeft = view.findViewById(R.id.iv_home_left);
        tvHomeLogin = view.findViewById(R.id.tv_home_login);
        ivHomeLogin = view.findViewById(R.id.iv_home_login);
        banner = view.findViewById(R.id.banner_text);
        recyclerViewHot = view.findViewById(R.id.recyclerViewHot);
        recyclerViewNew = view.findViewById(R.id.recyclerViewNew);
        recyclerViewRecommend = view.findViewById(R.id.recyclerViewRecommend);
        gridView = view.findViewById(R.id.gridView);
    }

    private void initRecyclerViews() {
        // 设置固定大小优化性能
        recyclerViewHot.setHasFixedSize(true);
        recyclerViewNew.setHasFixedSize(true);
        recyclerViewRecommend.setHasFixedSize(true);

        hotAdapter = new GoodsAdapter(hotGoodses);
        newAdapter = new GoodsAdapter(newGoodses);
        recommendAdapter = new GoodsAdapter(recommendGoodses);

        GridLayoutManager hotLayoutManager = new GridLayoutManager(mContext, 2);
        GridLayoutManager newLayoutManager = new GridLayoutManager(mContext, 2);
        GridLayoutManager recommendLayoutManager = new GridLayoutManager(mContext, 2);

        recyclerViewHot.setLayoutManager(hotLayoutManager);
        recyclerViewNew.setLayoutManager(newLayoutManager);
        recyclerViewRecommend.setLayoutManager(recommendLayoutManager);

        recyclerViewHot.setAdapter(hotAdapter);
        recyclerViewNew.setAdapter(newAdapter);
        recyclerViewRecommend.setAdapter(recommendAdapter);

        // 禁用嵌套滚动以优化性能
        recyclerViewHot.setNestedScrollingEnabled(false);
        recyclerViewNew.setNestedScrollingEnabled(false);
        recyclerViewRecommend.setNestedScrollingEnabled(false);

        gridAdapter = new GridViewAdapter(mContext);
        gridView.setAdapter(gridAdapter);
    }

    private void setupListeners() {
        svHome.setOnScrollChangeListener((NestedScrollView.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> {
            if (scrollY > 200) {
                hometop.setBackgroundResource(R.color.top);
                ivHomeLeft.setImageResource(R.drawable.ic_menu);
                tvHomeLogin.setTextColor(getResources().getColor(android.R.color.white));
                ivHomeLogin.setImageResource(R.drawable.ic_person_white);
            } else {
                hometop.setBackgroundColor(getResources().getColor(android.R.color.transparent));
                ivHomeLeft.setImageResource(R.drawable.ic_menu2);
                tvHomeLogin.setTextColor(getResources().getColor(R.color.top));
                ivHomeLogin.setImageResource(R.drawable.ic_person);
            }
        });

        View svsearch = rootView.findViewById(R.id.tv_home_search);
        svsearch.setOnClickListener(v -> navigateToSearchFragment());

        ivHomeLeft.setOnClickListener(v -> {
            if (getActivity() != null) {
                ((MainActivity) getActivity()).navigateToTypeFragment();
            }
        });

        tvHomeLogin.setOnClickListener(v -> {
            // 创建启动LoginActivity的Intent
            Intent intent = new Intent(getActivity(), login.class);
            intent.putExtra("from_home", true);
            startActivity(intent); // 启动登录Activity
        });
    }

    private void loadData() {
        if (isLoading) return;

        isLoading = true;
        executorService.execute(this::fetchData);
    }

    private void fetchData() {
        HttpURLConnection conn = null;
        try {
            URL url = new URL("http://47.99.134.126:28019/api/v1/index-infos");
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(8000);
            conn.setReadTimeout(8000);

            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream is = conn.getInputStream();
                String result = readStream(is);
                parseJson(result);
                handler.sendEmptyMessage(1);
            } else {
                handler.sendEmptyMessage(0);
            }
        } catch (IOException e) {
            Log.e(TAG, "Network error", e);
            handler.sendEmptyMessage(0);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
            isLoading = false;
        }
    }

    private String readStream(InputStream is) throws IOException {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        }
        return sb.toString();
    }

    private void parseJson(String json) {
        try {
            carousels.clear();
            hotGoodses.clear();
            newGoodses.clear();
            recommendGoodses.clear();

            JSONObject root = new JSONObject(json);
            JSONObject data = root.getJSONObject("data");

            JSONArray carouselArray = data.getJSONArray("carousels");
            for (int i = 0; i < carouselArray.length(); i++) {
                JSONObject obj = carouselArray.getJSONObject(i);
                carousels.add(new Carousel(
                        obj.getString("carouselUrl"),
                        obj.getString("redirectUrl")
                ));
            }

            parseGoodsArray(data.getJSONArray("hotGoodses"), hotGoodses);
            parseGoodsArray(data.getJSONArray("newGoodses"), newGoodses);
            parseGoodsArray(data.getJSONArray("recommendGoodses"), recommendGoodses);

        } catch (JSONException e) {
            Log.e(TAG, "JSON parsing error", e);
            handler.sendEmptyMessage(0);
        }
    }

    private void parseGoodsArray(JSONArray array, List<Goods> list) throws JSONException {
        for (int i = 0; i < array.length(); i++) {
            JSONObject obj = array.getJSONObject(i);
            list.add(new Goods(
                    obj.getInt("goodsId"),
                    obj.getString("goodsName"),
                    obj.getString("goodsIntro"),
                    obj.getString("goodsCoverImg"),
                    obj.getDouble("sellingPrice"),
                    obj.getString("tag")
            ));
        }
    }

    private void updateUI() {
        if (!isViewCreated || getView() == null) return;

        try {
            // 更新轮播图
            List<String> imageUrls = new ArrayList<>();
            for (Carousel carousel : carousels) {
                imageUrls.add(carousel.carouselUrl);
            }

            banner.setAdapter(new BannerImageAdapter<String>(imageUrls) {
                @Override
                public void onBindView(BannerImageHolder holder, String imagePath, int position, int size) {
                    Glide.with(mContext)
                            .load(imagePath)
                            .into(holder.imageView);
                }
            });

            // 更新适配器
            hotAdapter.notifyDataSetChanged();
            newAdapter.notifyDataSetChanged();
            recommendAdapter.notifyDataSetChanged();
            gridAdapter.notifyDataSetChanged();

        } catch (Exception e) {
            Log.e(TAG, "UI update error", e);
        }
    }

    private void navigateToSearchFragment() {
        try {
            FragmentManager fragmentManager = getParentFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.frameLayout, new SearchFragment())
                    .addToBackStack(null)
                    .commit();
        } catch (Exception e) {
            Log.e(TAG, "Navigation error", e);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "HomeFragment: onDestroyView");
        isViewCreated = false;

        // 释放资源
        handler.removeCallbacksAndMessages(null);
        executorService.shutdownNow();

        // 清除Glide请求
        if (getView() != null) {
            Glide.with(this).clear(banner);
        }
    }

    static class Carousel {
        final String carouselUrl;
        final String redirectUrl;

        Carousel(String carouselUrl, String redirectUrl) {
            this.carouselUrl = carouselUrl;
            this.redirectUrl = redirectUrl;
        }
    }

    public static class Goods {
        public final int goodsId;
        public final String goodsName;
        public final String goodsIntro;
        public final String goodsCoverImg;
        public final double sellingPrice;
        public final String tag;

        public Goods(int goodsId, String goodsName, String goodsIntro, String goodsCoverImg,
                     double sellingPrice, String tag) {
            this.goodsId = goodsId;
            this.goodsName = goodsName;
            this.goodsIntro = goodsIntro;
            this.goodsCoverImg = goodsCoverImg;
            this.sellingPrice = sellingPrice;
            this.tag = tag;
        }
    }

    class GoodsAdapter extends RecyclerView.Adapter<GoodsAdapter.ViewHolder> {
        private final List<Goods> goodsList;

        GoodsAdapter(List<Goods> goodsList) {
            this.goodsList = goodsList;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_goods, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            Goods goods = goodsList.get(position);
            holder.tvName.setText(goods.goodsName);
            holder.tvPrice.setText(String.format("￥%.2f", goods.sellingPrice));

            Glide.with(mContext)
                    .load(goods.goodsCoverImg)
                    .placeholder(R.drawable.ic_placeholder)
                    .error(R.drawable.ic_error)
                    .into(holder.ivImage);

            holder.itemView.setOnClickListener(v -> {
                if (getActivity() != null) {
                    Intent intent = new Intent(getActivity(), GoodsDetailActivity.class);
                    intent.putExtra("goodsId", goods.goodsId);
                    startActivity(intent);
                }
            });
        }

        @Override
        public int getItemCount() {
            return goodsList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            final ImageView ivImage;
            final TextView tvName, tvPrice;

            ViewHolder(@NonNull View itemView) {
                super(itemView);
                ivImage = itemView.findViewById(R.id.iv_goods_cover);
                tvName = itemView.findViewById(R.id.tv_goods_name);
                tvPrice = itemView.findViewById(R.id.tv_goods_price);
            }
        }
    }
}